﻿using System;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using System.IO;

namespace CoolCode.Web.Mvc.UI.Grid
{
	/// <summary>
	/// Renders links for sortable column headers in a sorted grid based on current HttpRequest params and column state.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public class SortableLinkRenderer<T> where T : class
	{
		private readonly HttpRequestBase _request;
		private readonly RequestContext _requestContext;
		private readonly IGridModel<T> _gridModel;
		private readonly GridColumn<T> _column;
		private Func<string> _urlBuilder;
		private string _onclick = null;
		private readonly RouteValueDictionary _routeValues;

		private string _controllerName;
		private string _actionName;

		public SortableLinkRenderer(IGridModel<T> gridModel, GridColumn<T> column, RenderingContext context)
		{
			_gridModel = gridModel;
			_column = column;
			_request = context.ViewContext.RequestContext.HttpContext.Request;
			_requestContext = context.ViewContext.RequestContext;
			_routeValues = context.ViewContext.RouteData.Values;
			_controllerName = (string)_routeValues["controller"];
			_actionName = (string)_routeValues["action"];
			_urlBuilder = CreateDefaultUrl;
		}

		/// <summary>
		/// The link to use in a sortable column that will provide data to help sort the underlying grid's data source.
		/// </summary>
		/// <returns>an html hyperlink tag with the url and name set.</returns>
		public string SortLink()
		{
			//string qs = SortQueryString();
			//string baseUrl = _request.Path;
			//return String.Format("<a href=\"{0}{1}\">{2}</a>"
			//                     , baseUrl
			//                     , qs
			//                     , _column.DisplayName);

			return renderPageLink(_column.DisplayName);
		}
		/*
		private string SortQueryString()
		{
			string additionalParams = AdditionalParametersQuery(_request);
			string qsFormat = "?{0}={1}&{2}={3}{4}";
			return String.Format(qsFormat
								 , _column.SortOptions.SortByQueryParameterName
								 , _column.Name
								 , _column.SortOptions.SortOrderQueryParameterName
								 , _column.SortOptions.SortOrder
								 , additionalParams);
		}

		private string AdditionalParametersQuery(HttpRequestBase request)
		{
			string additionalParams = String.Empty;
			foreach (string key in request.QueryString.Keys)
			{
				if (
					key.ToLower().Equals(_column.SortOptions.SortOrderQueryParameterName, StringComparison.InvariantCultureIgnoreCase) ==
					false &&
					key.ToLower().Equals(_column.SortOptions.SortByQueryParameterName, StringComparison.InvariantCultureIgnoreCase) ==
					false)
				{
					additionalParams += String.Format("&{0}={1}", key, request.QueryString[key]);
				}
			}
			return additionalParams;
		}
		*/

		protected virtual string CreateDefaultUrl()
		{
			var queryString = _request.QueryString;
			var dict = new RouteValueDictionary(_routeValues);

			//保留查询字符到下一页
			foreach (string key in queryString.Keys)
				dict[key] = queryString[key];

			//Sort
			dict[_gridModel.SortByQueryStringName]= _column.Name;
			dict[_gridModel.SortOrderQueryStringName]=_column.SortOptions.SortOrder;

			UrlHelper urlHelper = new UrlHelper(_requestContext);
			string url = urlHelper.Action(_actionName, dict);
			return url;
		}

		private string renderPageLink(string displayText)
		{
			StringWriter output = new StringWriter();
			if (string.IsNullOrEmpty(_onclick))
			{
				output.Write("<a href=\"{0}\">{1}</a>", _urlBuilder(), displayText);
			}
			else
			{
				output.Write("<a href=\"{0}\" onclick=\"{2}\">{1}</a>", _urlBuilder(), displayText, _onclick);
			}

			return output.ToString();
		}

		public SortableLinkRenderer<T> OnClick(string script) 
		{
			_onclick = script;
			return this;
		}
	}
}